#include "worker_thread.hpp"
#include "events_config.hpp"
#include "events_cb.hpp"
#include "thread_task.hpp"
#include "error_check.hpp"
#include <cassert>
#include <glog/logging.h>
#include <event2/event.h>
#include <thread>

worker_thread::worker_thread(/* args */)
{
}

worker_thread::~worker_thread()
{
}
void worker_thread::notify(int fd,short ev)
{
    char buf[2] = {0};
    int ret = read(fd,buf,2);
    if(ret <= 0)
    {
        VLOG(3)<<"pipe error"<<std::this_thread::get_id();
    }
    VLOG(0)<<"accept tcp "<<buf;
    if (this->m_tasks.empty())
    {
        VLOG(2)<<"get tasks error   "<<this->m_t_id;
        return ;
    }
    thread_task *work_task = nullptr;
    m_tasks_mutex.lock();
    work_task = m_tasks.front();
    m_tasks.pop_front();
    m_tasks_mutex.unlock();
    VLOG(0)<<"get task";
    work_task->init();


}
void worker_thread::event_funcb(evutil_socket_t fd, short which, void *arg)
{
                                            // 激活线程任务的回调函数
    worker_thread* th =(worker_thread*)arg;
    VLOG(0)<<"notify event_funcb";
    th->notify(fd,which);
                                            // 选择水平触发，只读一个字符即可
  
}
void worker_thread::setup()
{
   int pipes[2];
    if(pipe(pipes))
    {
         VLOG(3) <<"pipe failed";
         return ;
    }
    m_notify_send_fd = pipes[1];              // 存入写端的文件描述符
    
    events_config config;
    config.set_event_config();
    auto p = config.get_event_config();
    this->m_base = event_base_new_with_config(p);

                                            // 添加管道事件
    event *ev = event_new(m_base,pipes[0],EV_READ|EV_PERSIST,events_cb::event_worker_cb,this);
    
    event_add(ev,0);
    
    if(!m_base)
    {
        VLOG(3) << "config thread no lock is error";
    }
}
void worker_thread::start()
{
    setup();
    std::thread th(&worker_thread::thread_func,this);
    th.detach();
}
void worker_thread::thread_func()
{
    VLOG(0)<<"create pthread  "<<std::this_thread::get_id()<<"  "<<get_pthread_id(); 
    event_base_dispatch(m_base);
    event_base_free(m_base);
}

void worker_thread::set_pthread_id(int pthread_id)
{
    this->m_t_id = pthread_id;
}
int worker_thread::get_pthread_id()
{
    return this->m_t_id;
}
void worker_thread::activate()
{
    int ret = write(this->m_notify_send_fd,"c",1);
    if(ret == -1)
    {
        VLOG(0)<<"write error";
    }
    else
    {
        VLOG(0)<<"write pipe "<<ret;
    }
}
void worker_thread::add_task(thread_task* tasks)
{
    if(!tasks)  return;
    tasks->m_base = this->m_base;

    m_tasks_mutex.lock();
    m_tasks.push_back(tasks); // 加入到任务队列中去
    m_tasks_mutex.unlock();
    VLOG(0)<<"add the task to the task list";
}